var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
var Layer=require('./layer');
var Route=module.exports=function(path){
    this.path=path;
    this.stack=[];
    this.methods = {};
}
//done 是Router handle next
Route.prototype.dispatch=function(req,res,done){
    console.log('route prototype dispatch');
    var idx = 0;
    var stack = this.stack;
    if (stack.length === 0) {
        return done();
    }
    var method = req.method.toLowerCase();
    if (method === 'head' && !this.methods['head']) {
        method = 'get';
    }
    req.route = this;
    next();
    function next(err){
        console.log('route diapatch next idx',idx,'err',err)
        if (err && err === 'route') {
            return done();
        }
        if (err && err === 'router') {
            return done(err)
        }
        var layer = stack[idx++];
        console.log('route dispatch layer',idx,layer && layer.handle && layer.handle.toString());
        if (!layer) {
            console.log('run done')
            return done(err);
        }
        if (layer.method && layer.method !== method) {
            return next(err);
        }
        if (err) {
            layer.handle_error(err, req, res, next);
        } else {
            layer.handle_request(req, res, next);
        }
    }
}
Route.prototype.get=function(){
    var handles = Array.prototype.slice.call(arguments);
    console.log('Route.prototype.get',handles)
    for (var i = 0; i < handles.length; i++) {
        var handle = handles[i];
        if (typeof handle !== 'function') {
            var type = toString.call(handle);
            var msg = 'Route.' + method + '() requires a callback function but got a ' + type
            throw new Error(msg);
        }
        var layer=new Layer('/',{},handle);
        layer.method='get';
        this.methods.get=true;
        this.stack.push(layer);
    }
    return this;
}